package com.huzz.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.entity.SysDepartment;
import com.huzz.mapper.SysDepartmentMapper;
import com.huzz.model.SysDepartmentCreateModel;
import com.huzz.model.SysDepartmentQueryModel;
import com.huzz.model.SysDepartmentUpdateModel;
import com.huzz.service.ISysDepartmentService;
import com.huzz.util.entityutil.FieldUtil;
import com.huzz.util.entityutil.ModelUtil;
import com.huzz.util.tree.TreeBuilder;
import com.huzz.vo.SysDepartmentVO;
import com.huzz.util.body.DataBox;
import com.huzz.util.body.ResultCode;
import com.huzz.util.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 系统部门-业务实现层
 *
 * @author 童年的纸飞机
 * @since 2023-06-07 11:25
 */
@Service
@Slf4j
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {

    /**
     * 系统部门Mapper
     */
    @Autowired
    private SysDepartmentMapper sysDepartmentMapper;

    /**
     * 根据进行ID查询SysDepartment
     *
     * @param id
     * @return
     */
    @Override
    public SysDepartment getSysDepartmentById(Integer id) {
        return sysDepartmentMapper.selectById(id);
    }

    /**
     * 新增SysDepartment
     *
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean createSysDepartment(SysDepartmentCreateModel model) {

        SysDepartment sysDepartment = ModelUtil.transToSimilarEntity(model, SysDepartment.class);
        FieldUtil.setCreatedAndUpdateField(sysDepartment);

        return sysDepartmentMapper.insert(sysDepartment) > 0;
    }

    /**
     * 更新SysDepartment
     *
     * @param model
     * @return
     */
    @Override
    @Transactional
    public boolean updateSysDepartment(SysDepartmentUpdateModel model) {
        if (sysDepartmentMapper.selectById(model.getId()) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "更新对象不存在");
        }

        SysDepartment sysDepartment = ModelUtil.transToSimilarEntity(model, SysDepartment.class);
        FieldUtil.setUpdateField(sysDepartment);

        return sysDepartmentMapper.updateById(sysDepartment) > 0;
    }

    /**
     * 根据ID进行删除SysDepartment
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteSysDepartmentById(Integer id) {
        if (sysDepartmentMapper.selectById(id) == null) {
            throw new BizException(ResultCode.COMMON_FAIL.getCode(), "删除对象不存在");
        }
        // 删除子集
        List<Integer> cIds = TreeBuilder.builderAllChildrenIds(id, sysDepartmentMapper);
        sysDepartmentMapper.deleteBatchIds(cIds);

        return sysDepartmentMapper.deleteById(id) > 0;
    }

    /**
     * 查询SysDepartment列表
     *
     * @param model
     * @return
     */
    @Override
    public List<SysDepartmentVO> selectSysDepartmentList(SysDepartmentQueryModel model) {

        return sysDepartmentMapper.selectSysDepartmentVOList(getQueryWrapper(model));
    }

    @Override
    public List<SysDepartmentVO> selectSysDepartmentTree(SysDepartmentQueryModel model) {

        return TreeBuilder.builderTree(sysDepartmentMapper, getQueryWrapper(model), SysDepartmentVO.class);
    }

    /**
     * 导出SysDepartment列表
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @Override
    public void exportSysDepartmentExcel(HttpServletRequest request, HttpServletResponse response, SysDepartmentQueryModel model) {
        QueryWrapper<SysDepartment> wrapper = getQueryWrapper(model);

        List<SysDepartmentVO> data = sysDepartmentMapper.selectSysDepartmentVOList(wrapper);

        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("系统部门列表", "SysDepartmentVO"), SysDepartmentVO.class, data);
        String fileName = String.format("系统部门_%d.xls", System.currentTimeMillis());
        response.setHeader("Content-Disposition", "attachment;Filename=" + fileName);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 批量编辑SysDepartment
     *
     * @param modelList
     * @return
     */
    @Override
    public DataBox<String> updateSysDepartmentByList(List<SysDepartmentUpdateModel> modelList) {
        List<SysDepartment> sysDepartmentList = ModelUtil.transToSimilarList(modelList, SysDepartment.class);
        int i = 0;
        for (SysDepartment sysDepartment : sysDepartmentList) {
            FieldUtil.setUpdateField(sysDepartment);
            i += sysDepartmentMapper.updateById(sysDepartment);
        }

        return i > 0 ?
                DataBox.failedBuilder("共" + i + "条记录更新成功, " + (sysDepartmentList.size() - i) + "条记录更新失败") : DataBox.failedBuilder("更新失败");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public DataBox<String> deleteSysDepartmentByIds(List<Integer> ids) {
        int i = sysDepartmentMapper.deleteBatchIds(ids);
        return i > 0 ?
                DataBox.succeedBuilder("共" + i + "条记录被删除, " + (ids.size() - i) + "条记录删除失败") : DataBox.failedBuilder("删除失败");
    }

    /**
     * 查询条件
     *
     * @param model
     * @return
     */
    private QueryWrapper<SysDepartment> getQueryWrapper(SysDepartmentQueryModel model) {
        QueryWrapper<SysDepartment> wrapper = new QueryWrapper<>();

        // 根据 ids 进行查询
        if (model.getIds() != null && model.getIds().length > 0) {
            wrapper.lambda().in(SysDepartment::getId, model.getIds());
        }
        // 根据 更新时间区间 进行查询
        if (model.getTimeInterval() != null && model.getTimeInterval().length == 2) {
            wrapper.lambda().between(SysDepartment::getUpdateTime, model.getTimeInterval()[0], model.getTimeInterval()[1]);
        }
        // 根据 部门名称 进行查询
        if (!StringUtils.isEmpty(model.getName())) {
            wrapper.lambda().like(SysDepartment::getName, model.getName());
        }
        // 根据 状态(1开启,0关闭) 进行查询
        if (null != model.getStatus()) {
            wrapper.lambda().eq(SysDepartment::getStatus, model.getStatus());
        }
        // 根据 父级id(默认0为根部门) 进行查询
        if (null != model.getParentId()) {
            wrapper.lambda().eq(SysDepartment::getParentId, model.getParentId());
        }
        // 根据 部门电话 进行查询
        if (!StringUtils.isEmpty(model.getPhone())) {
            wrapper.lambda().eq(SysDepartment::getPhone, model.getPhone());
        }
        // 根据 更新时间 进行降序
        wrapper.lambda().orderByDesc(SysDepartment::getUpdateTime);


        return wrapper;
    }

}